package com.chiaching.framwork.config;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import sun.util.logging.resources.logging;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;

/**
 * @author jiajing.he
 * @date 2021/4/4 10:18
 */
@Configuration
@ConditionalOnProperty(name = "logback.enable",havingValue = "true")
@Slf4j
public class LogbackConfig {


    @Value("${logback.context}")
    public String info;

    @PostConstruct
    public void init(){
      if (StrUtil.isNotBlank(info)){
          LoggerContext iLoggerFactory = (LoggerContext)LoggerFactory.getILoggerFactory();
          try {
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(info.getBytes());
              JoranConfigurator joranConfigurator = new JoranConfigurator();
              iLoggerFactory.reset();
              joranConfigurator.setContext(iLoggerFactory);
              joranConfigurator.doConfigure(byteArrayInputStream);
          } catch (JoranException e) {
              e.printStackTrace();
          }
          StatusPrinter.printInCaseOfErrorsOrWarnings(iLoggerFactory);
      }
    }


}
